package com.wuxx.quartz.trigger.factory;

import com.wuxx.quartz.model.CronTimingModel;
import com.wuxx.quartz.model.TimingModel;
import com.wuxx.quartz.model.TriggerType;
import com.wuxx.quartz.trigger.ITriggerFactory;
import org.nutz.ioc.loader.annotation.IocBean;
import org.quartz.CronScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;

@IocBean
public class CronTrigger implements ITriggerFactory {
    @Override
    public boolean check(TriggerType triggerType) {
        return triggerType==TriggerType.CRON;
    }

    @Override
    public Trigger build(TimingModel timingModel) {
        if (!(timingModel instanceof CronTimingModel)){
            throw new RuntimeException("构建类型为CRON定时必须传入CronTimingModel.class的实现类");
        }
        //按新的cronExpression表达式构建一个新的trigger
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(((CronTimingModel) timingModel).getCronExpression());
        return TriggerBuilder.newTrigger().withIdentity(timingModel.getTaskName(),timingModel.getGroupName())
                .withSchedule(scheduleBuilder).build();
    }
}
